package com.carskeeper.controller.body;

import com.alibaba.dubbo.config.annotation.Reference;
import com.carskeeper.body.service.BodyCarOwnerService;
import com.carskeeper.common.dtos.PageResponseResult;
import com.carskeeper.common.dtos.ResponseResult;
import com.carskeeper.model.body.dtos.QueryOwnerDto;
import com.carskeeper.model.body.dtos.UpdateStatusDto;
import com.carskeeper.model.body.vo.BodyCarOwnerVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.mapstruct.Context;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@Api(tags = "车主主体" )
@RestController
@RequestMapping("/body/carowner")
public class BodyCarOwnerController {

    @Reference(check = false)
    private BodyCarOwnerService bodyCarOwnerService;

    /**
     * 分页条件查询车主主体信息
     * @param dto
     * @return
     */
    @ApiOperation("查询车主主体")
    @PostMapping("findByPage")
    public PageResponseResult<List<BodyCarOwnerVo>> findOwnerByPage(@RequestBody QueryOwnerDto dto){
        return bodyCarOwnerService.findOwnerByPage(dto);
    }


    /**
     * 修改车主状态
     * @param dto
     * @return
     */
    @ApiOperation("修改车主状态")
    @PostMapping("updateStatus")
    public ResponseResult updateStatus(@RequestBody UpdateStatusDto dto){
        return bodyCarOwnerService.updateOwnerStatus(dto);
    }

    /**
     * 导出车主信息
     * @param name
     * @param phone
     * @param status
     * @param page
     * @param pageSize
     * @param response
     * @throws IOException
     */
    @ApiOperation("导出车主信息")
    @GetMapping("export")
    public void exportOwner(@RequestParam(required = false) String name,
                            @RequestParam(required = false) String phone,
                            @RequestParam(required = false) Short status,
                            @RequestParam(defaultValue = "1") Integer page,
                            @RequestParam(defaultValue ="10")Integer pageSize,
                            @Context HttpServletResponse response
                            ) throws IOException {
        QueryOwnerDto dto = new QueryOwnerDto(name, phone, status, page, pageSize);

        //获取响应对象response，设置文件下载的头信息
        response.setHeader("Content-disposition", "attachment;filename=Attendance.xls");
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        String filename = bodyCarOwnerService.exportOwner(dto);
        BufferedInputStream bf= new BufferedInputStream(new FileInputStream(filename));
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] buffer = new byte[1024];
        int bytesRead=0;
        while ((bytesRead = bf.read(buffer)) != -1) {
            //将读取的字节转为字符串对象
            outputStream.write(buffer,0,bytesRead);
        }
    }
}
